package com.zhiwei.most.ext

import android.view.View
import androidx.annotation.StringRes
import androidx.appcompat.widget.AppCompatTextView
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.ViewUtils
import com.jakewharton.rxbinding4.view.clicks
import com.zhiwei.most.R
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import java.lang.reflect.ParameterizedType
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * Create by zhiweizhu on 2022/2/24
 */
/**
 * 判断是否为空 并传入相关操作
 */
inline fun <reified T> T?.notNull(notNullAction: (T) -> Unit, nullAction: () -> Unit = {}) {
    if (this != null) {
        notNullAction.invoke(this)
    } else {
        nullAction.invoke()
    }
}


/**
 * 获取当前类绑定的泛型ViewModel-clazz
 */
fun <VM> getVmClazz(obj: Any): VM {
    return (obj.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as VM
}



/**
 * 倒计时
 */
@ExperimentalCoroutinesApi
fun countDownCoroutines(
    total: Int,
    onTick: (Int) -> Unit,
    onFinish: () -> Unit,
    delayTime: Long = 1000L,
    scope: CoroutineScope = GlobalScope,
    sort: Boolean = false
): Job {
    return flow {
        if(sort){
            for (value in 0..total){
                emit(value)
                delay(delayTime)
            }
        }else {
            for (i in total downTo 0) {
                emit(i)
                delay(delayTime)
            }
        }
    }.flowOn(Dispatchers.Default) //flowOn只影响该运算符之前的CoroutineContext，对它之后的CoroutineContext没有任何影响
        .onEach { onTick.invoke(it) } //每个值释放的时候可以执行的一段代码
        .onCompletion { onFinish.invoke() } //最后一个值释放完成之后被执行
        .catch { e -> println(e) } //catch函数能够捕获之前产生的异常，之后的异常无法捕获
        .flowOn(Dispatchers.Main)
        .launchIn(scope) //scope.launch { flow.collect() }的缩写, 代表在某个协程上下文环境中去接收释放的值
}








